import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;

import java.io.File;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * FileChannel 从文件读取数据
 * DatagramChannel 通过UDP读写网络中的数据
 * SocketChannel 通过TCP读写网络中的数据
 * ServerSocketChannel 监听新进来的TCP连接，像web服务器那样。对每个新进来的连接都会创建一个SocketChannel
 */

@Slf4j
public class FileChannelDemo {

    @Test
    public void fileChannelRead() throws Exception {
        File file = new File("C:\\gitee\\spring-cloud-demo\\spring-cloud-nio\\src\\test\\java\\test.text");

        RandomAccessFile randomAccessFile = new RandomAccessFile(file,"rw");
        FileChannel channel = randomAccessFile.getChannel();
        //创建Buffer
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);

        int readByteBuffer = channel.read(byteBuffer);
        while (readByteBuffer!=-1){
            log.info("读取了:{}",readByteBuffer);
            byteBuffer.flip();
            while (byteBuffer.hasRemaining()){
                log.info("{}",(char)byteBuffer.get());
            }
            byteBuffer.clear();
            readByteBuffer = channel.read(byteBuffer);
        }

        randomAccessFile.close();
        log.info("读取文件结束");
    }

    @Test
    public void fileChannelWrite() throws Exception {
        File file = new File("C:\\gitee\\spring-cloud-demo\\spring-cloud-nio\\src\\test\\java\\test.text");

        RandomAccessFile randomAccessFile = new RandomAccessFile(file,"rw");
        FileChannel channel = randomAccessFile.getChannel();

        String msg = "new data";

        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);

        byteBuffer.clear();

        byteBuffer.put(msg.getBytes());

        byteBuffer.flip();

        while (byteBuffer.hasRemaining()){
            channel.write(byteBuffer);
        }

        channel.close();
        randomAccessFile.close();
        log.info("写文件结束");
    }

    @Test
    public void fileChannelPosition() throws Exception {
        File file = new File("C:\\gitee\\spring-cloud-demo\\spring-cloud-nio\\src\\test\\java\\test.text");

        RandomAccessFile randomAccessFile = new RandomAccessFile(file,"rw");
        FileChannel channel = randomAccessFile.getChannel();
        log.info("fileSize:{}",channel.size());

        channel.close();
        randomAccessFile.close();
    }

}
